package jwanalytics.dbloader;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import jwanalytics.dbloader.DB;
import jwanalytics.dbloader.Props;

import org.apache.log4j.Logger;


/** 
 * 
 * When the main method of this class is run it will recreate whole
 * database.  It will erase all data of the current database!  It will
 * prompt the user to ensure it is really what he wishes.
 */
public class RecreateDatabase {
	
	/** Logger for all pages. */
	public static Logger logger = Logger.getLogger("jwanalytics");
	
	/**
	 * Recreates the whole wicket analytics databases even loosing the values
	 * of sequences, etc.
	 * @param args
	 */
	public static void main(String[] args) {
		Props.init(Props.PROPS_FILE, false);
		// TODO Auto-generated method stub
		System.out.println("This will erase your analytics database!");
		System.out.println("It will also reset your database sequences (including unique session id counters).");
		System.out.println("Do you wish to continue? Type: Y/N.");
		System.out.println("Any answer containing Y will proceed.");
		System.out.println("Any answer containing N will cancel.");
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
		String answer = null;
		try { 
			answer = br.readLine();
	    	System.out.println("Your answer was:"+answer);
	    	if (answer.toUpperCase().indexOf("Y") == -1) {
	    		System.out.println("Cancelling.");
	    		System.exit(1);
	    	} else {
	    		System.out.println("Proceeding.");
	    		try {
	    			proceed();
	    		} catch(Exception e) {
	    			logger.error("WAERROR0006:Error while creating database:"+e);
	    			e.printStackTrace(); //always print in debug or deployment mode.				    			
	    		}
	    	}			
	    } catch (IOException ioe) { 
	    	logger.error("WAERROR0007:Could not capture command.  Cancelling.");
	    	System.exit(1);
	    } 
	}
	
	/** This proceeds with the database creation. 
	 * @throws Exception */
	public static void proceed() throws Exception {
		logger.debug("Starting database creation, this might take a few minutes...");
		//
		logger.debug("Dropping tables.");
		DeletePartsOfDatabase.deleteTableList(DeletePartsOfDatabase.tableList);
		DeletePartsOfDatabase.dropTableList(DeletePartsOfDatabase.tableList);
		logger.debug("Dropping sequences.");		
		DeletePartsOfDatabase.dropSequenceList(DeletePartsOfDatabase.sequenceList);
		logger.debug("Recreating sequences.");				
		executeStatement(Props.get(Props.PROPS_FILE, "c_customer_sequence.create_sequence_ddl"));
		executeStatement(Props.get(Props.PROPS_FILE, "c_client_system_sequence.create_sequence_ddl"));
		executeStatement(Props.get(Props.PROPS_FILE, "c_page_sequence.create_sequence_ddl"));
		executeStatement(Props.get(Props.PROPS_FILE, "c_page_fact_sequence.create_sequence_ddl"));
		executeStatement(Props.get(Props.PROPS_FILE, "c_referer_sequence.create_sequence_ddl"));		
		executeStatement(Props.get(Props.PROPS_FILE, "c_returning_browser_sequence.create_sequence_ddl"));
		executeStatement(Props.get(Props.PROPS_FILE, "c_session_sequence.create_sequence_ddl"));
		logger.debug("Recreating tables.");						
		executeStatement(Props.get(Props.PROPS_FILE, "client_system_dimension.create_table_ddl"));
		executeStatement(Props.get(Props.PROPS_FILE, "client_system_dimension.create_index_user_agent_ddl"));
		executeStatement(Props.get(Props.PROPS_FILE, "session_dimension.create_table_ddl"));
		executeStatement(Props.get(Props.PROPS_FILE, "customer_dimension.create_table_ddl"));
		try { 
			executeStatement(Props.get(Props.PROPS_FILE, "customer_dimension.insert_unknown_customer"));
		} catch(Exception e) {
			//we avoid dropping this table as it has the customers and we try to insert entry with id zero for the "Customer not known".
			//but if it fails (statement above) we assume it is because such entry already exists.
		}
		logger.debug("Executing populate date dimension. This might take a while...");
		PopulateDateDimension.main(null);
		logger.debug("Executing populate time of day dimension.");		
		PopulateTimeOfDayDimension.main(null);
		executeStatement(Props.get(Props.PROPS_FILE, "returning_browser_dimension.create_table_ddl"));     //Has to be after date.
		executeStatement(Props.get(Props.PROPS_FILE, "returning_browser_dimension.create_index_cookie_date_ddl"));
		executeStatement(Props.get(Props.PROPS_FILE, "page_dimension.create_table_ddl"));
		executeStatement(Props.get(Props.PROPS_FILE, "page_dimension.create_index_page_ddl"));
		executeStatement(Props.get(Props.PROPS_FILE, "referer_dimension.create_table_ddl"));
		executeStatement(Props.get(Props.PROPS_FILE, "referer_dimension.create_index_url_ddl"));		
		executeStatement(Props.get(Props.PROPS_FILE, "referer_dimension.create_index_domain_ddl"));				
		executeStatement(Props.get(Props.PROPS_FILE, "page_fact.create_table_ddl"));
		executeStatement(Props.get(Props.PROPS_FILE, "page_fact.create_index_web_server_date_ddl"));		
		executeStatement(Props.get(Props.PROPS_FILE, "page_fact.create_index_time_of_day_ddl"));				
		executeStatement(Props.get(Props.PROPS_FILE, "page_fact.create_index_page_ddl"));				
		executeStatement(Props.get(Props.PROPS_FILE, "page_fact.create_index_session_ddl"));				
		executeStatement(Props.get(Props.PROPS_FILE, "clickstream_page_event_fact.create_table_ddl"));					
		executeStatement(Props.get(Props.PROPS_FILE, "clickstream_page_event_fact.create_index_start_date_ddl"));
		executeStatement(Props.get(Props.PROPS_FILE, "clickstream_page_event_fact.create_index_referer_ddl"));		
		executeStatement(Props.get(Props.PROPS_FILE, "clickstream_page_event_fact.create_index_start_page_ddl"));				
		executeStatement(Props.get(Props.PROPS_FILE, "clickstream_page_event_fact.create_index_end_page_ddl"));
		executeStatement(Props.get(Props.PROPS_FILE, "clickstream_page_event_fact.create_index_returning_browser_ddl"));
		executeStatement(Props.get(Props.PROPS_FILE, "clickstream_page_event_fact.create_index_client_system_ddl"));
		executeStatement(Props.get(Props.PROPS_FILE, "clickstream_page_event_fact.create_index_ip_address_ddl"));
		executeStatement(Props.get(Props.PROPS_FILE, "clickstream_page_event_fact.create_index_is_returning_browser_ddl"));
		logger.debug("");
		logger.debug("DO NOT forget to cleanup the browser cookies also which refer to old database.");
	}
	
	/** Just a local method to print debugging information for this class. Before calling the DB class to
	 * execute the statement. 
	 * @throws Exception */
	public static void executeStatement(String statement) throws Exception {
		logger.debug("Executing:"+statement);
		DB.executeStatement(statement);
	}
	
}
